import logging
import os
import time
import colorlog
from logging.handlers import RotatingFileHandler
from utils.config import config

# 定义不同日志等级颜色
log_colors_config = {
    'DEBUG': 'bold_cyan',
    'INFO': 'bold_green',
    'WARNING': 'bold_yellow',
    'ERROR': 'bold_red',
    'CRITICAL': 'red',
}

# 创建文件目录
cur_path = os.path.dirname(config.log_dir())  # log_path是存放日志的路径
log_path = os.path.join(os.path.dirname(cur_path), 'logs')
if not os.path.exists(log_path):
    os.mkdir(log_path)  # 如果不存在这个logs文件夹，就自动创建一个

# 修改log保存位置
timestamp = time.strftime("%Y-%m-%d", time.localtime())
logfile_name = '%s-%s.log' % (config.access(), timestamp)
logfile_path = os.path.join(log_path, logfile_name)


class Logger(logging.Logger):
    def __init__(self, name, level=config.log_level(), file=None, encoding='utf-8'):
        super().__init__(name, )
        self.encoding = encoding
        self.file = file
        self.level = eval(level.upper())
        # 针对所需要的日志信息 手动调整颜色
        formatter_output = colorlog.ColoredFormatter(
            '%(asctime)s %(reset)s| %(message_log_color)s%(levelname)-8s %(reset)s| %('
            'log_color)s[%(filename)s%(reset)s:%(log_color)s%(module)s%(reset)s:%(log_color)s%(funcName)s%('
            'reset)s:%(log_color)s%(''lineno)d] %(reset)s- %(white)s%(message)s',
            reset=False,
            log_colors=log_colors_config,
            secondary_log_colors={
                'message': {
                    'DEBUG': 'blue',
                    'INFO': 'blue',
                    'WARNING': 'blue',
                    'ERROR': 'red',
                    'CRITICAL': 'bold_red'
                }
            },
            style='%'
        )  # 日志输出格式

        formatter = logging.Formatter(
            '{"timestamp": "%(asctime)s", "level": "%(levelname)-8s", "filename": %(filename)s, "module": "%(module)s",'
            ' "function": %(funcName)s, "line": "%(''lineno)d", "msg": "%(message)s"}'
        )

        # 创建一个FileHandler，用于写到本地
        rotatingFileHandler = logging.handlers.RotatingFileHandler(filename=logfile_path,
                                                                   maxBytes=1024 * 1024 * 50,
                                                                   backupCount=5)
        rotatingFileHandler.setFormatter(formatter)
        rotatingFileHandler.setLevel(logging.DEBUG)
        self.addHandler(rotatingFileHandler)
        # 创建一个StreamHandler,用于输出到控制台
        console = colorlog.StreamHandler()
        console.setLevel(logging.DEBUG)
        console.setFormatter(formatter_output)
        self.addHandler(console)
        self.setLevel(logging.DEBUG)


logger = Logger(name=logfile_path, file=logfile_path)
